<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { PropType } from 'vue'
import { PlusOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { useRoute } from 'vue-router'
import { useModalForm } from './useModalForm'
import { type ITableAction, useTableAction } from './useTableAction'
import BasePageLayout from '@/layouts/BasePageLayout.vue'
import type { FormOptions } from '@/components/ui/form/src/types/type'
import { removeEmptyInObject } from '@/utils'

const props = defineProps({
  // 搜索配置
  searchFormOptions: {
    default: () => [],
    type: Array as PropType<FormOptions[]>,
  },
  // 表单、表格、文本配置
  config: {
    default: () => ({}),
    require: true,
    type: Object as PropType<IconfigProps>,
  },
  // 接口配置
  apiConfig: {
    default: () => ({}),
    require: true,
    type: Object as PropType<ITableAction>,
  },
  // 回填时有些编辑表单项不可修改
  disabledEditOptions: {
    default: () => [],
    type: Array as PropType<string[]>,
  },
})

const emits = defineEmits(['submitForm', 'customRowEvent'])

const route = useRoute()

interface IconfigProps {
  columns: any[]
  text: Record<string, any>
  options: FormOptions[]
}

const hasDetail = computed(() => props.config.text.detailAction)

const formRef = ref()

const layout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } }

const searchFormRef = ref()
const searchFormModel = ref()
const configModalFormOptions = ref()

watch(() => props.config.options, (nVal: any) => {
  configModalFormOptions.value = nVal
}, { immediate: true })

const { visible, type, formModel, modalFormOptions, validatedForm, onClickAddModal, onClickEditModal, onClickSubmitForm, onClickResetForm }
  = useModalForm(formRef, configModalFormOptions, props.disabledEditOptions)

const { dataList, pagination, getLoading, addLoading, updateLoading, getList, onClickEditForm, onClickSubmitModalForm, onClickDeleteAction, deleteLoading }
  = useTableAction(props.apiConfig, searchFormModel, { visible, onClickEditModal })

watch(() => validatedForm.value, (nVal: boolean) => {
  if (nVal)
    onClickSubmitModalForm(formModel.value, type.value!)
})

// 自动保存搜索信息，和分页信息一起查询列表
watch(() => searchFormRef.value?.model, (nVal: any) => {
  searchFormModel.value = nVal
}, { deep: true })

function onClickSubmitSearchFrom() {
  const searchOptions = removeEmptyInObject(searchFormRef.value?.model)
  Object.assign(searchOptions, { pageNo: 1, pageSize: 10 })
  getList(searchOptions)
}

function customRowEvent(record: any) {
  const onClick = () => {
    emits('customRowEvent', record)
  }

  return { onClick }
}

defineExpose({ visible, onClickEditModal, formModel, dataList, getLoading, getList, pagination, onClickEditForm, deleteLoading, onClickDeleteAction })
</script>

<template>
  <BasePageLayout>
    <template #search>
      <GpForm v-if="searchFormOptions.length" ref="searchFormRef" :options="searchFormOptions" class="gp__grid-three" :showfooter="true">
        <template #footerAction>
          <a-button type="primary" @click="onClickSubmitSearchFrom">
            <SearchOutlined />{{ config.text.searchAction }}
          </a-button>
        </template>
      </GpForm>
    </template>
    <template #operate>
      <div class="gp__flex-start">
        <a-button type="primary" @click="onClickAddModal">
          <PlusOutlined />{{ config.text.addAction }}
        </a-button>
        <a-button v-if="config.text.refresh" class="gp__second-btn" @click="getList(route.query)">
          <ReloadOutlined />{{ config.text.refreshAction }}
        </a-button>
      </div>

      <GpModal
        v-model:visible="visible"
        :title="type === 'add' ? config.text.addModalTitle : config.text.editModalTitle"
        width="600px"
      >
        <template #content>
          <a-alert message="The fields marked with * are required" type="warning" show-icon style="margin-bottom: 20px" />
          <GpForm
            ref="formRef"
            v-bind="layout"
            :options="modalFormOptions"
          />
          <slot name="FormFooter" :data="formModel" :type="type" />
        </template>
        <template #footer>
          <div style="text-align: center">
            <a-button :disabled="type === 'edit'" @click="onClickResetForm">
              reset
            </a-button>
            <a-button style="margin-left: 15px" type="primary" :loading="addLoading || updateLoading" @click="onClickSubmitForm">
              submit
            </a-button>
          </div>
        </template>
      </GpModal>
    </template>
    <template #content>
      <a-table
        :class="{ 'page-form-table-content': hasDetail }"
        :loading="getLoading"
        :columns="props.config.columns"
        :data-source="dataList"
        :custom-row="customRowEvent" size="middle"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <slot name="customs" v-bind="{ column, record }" />
        </template>
      </a-table>
      <GpPagination v-if="!getLoading" :pagination="pagination" />
    </template>
  </BasePageLayout>
</template>

<style lang="less" scoped>
.page-form-table-content {
  ::v-deep(.ant-table-tbody) {
    cursor: pointer;
  }
}
</style>
